<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Model\Feedback;
use App\Model\Order;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Phper666\JWTAuth\JWT;
use App\Services\Wechat;
use App\Controller\AbstractController;


class FeedbackController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    protected JWT $jwt;
    protected Wechat $wechat;

    #[Inject]
    protected Feedback $feedback;

    public function __construct()
    {
        $this->jwt = container()->get(JWT::class);
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }
    /**列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
//        try {
            $page = $request->inputs(['page', 'limit', 'time','is_handle']);
            $query = $this->feedback->where(function ($query) use ($page) {
                if (array_key_exists('is_handle', $page) && $page['is_handle'] != '') {
                    $query->where('is_handle',$page['is_handle']);
                }
                if (isset($page['time'])) {
                    if(!is_array($page['time'])){
                        $page['time'] = json_decode($page['time'],true);
                    }
                    $query->where('created_at', '>=', $page['time'][0]);
                    $query->where('created_at', '<=', $page['time'][1]);
                }
            }) ->with(['order' => function ($query) {
                $query->select('id', 'number','sn'); // 只获取经销商id和name
            }])->orderBy('id', 'desc')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit']);
            $data['list'] = $query->get();
            $data['total'] = $query->count();
            return $this->success($data);
    }


    /**标记处理
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(RequestInterface $request):ResponseInterface
    {
        $data = $request->inputs(['id','is_handle']);
        try{
            $this->feedback->where('id',$data['id'])->update(['is_handle'=>$data['is_handle']]);
            return $this->success();
        }catch (\Exception $e){
            return $this->error();
        }
    }

}
